import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;


public class MySorter implements Runnable{
	private Queue<Data> queue;
	private ArrayList<HashMap<Integer, Data>> sorted;
	private DataFileStorer storer;

	public MySorter(DataFileStorer storer) {
		this.queue = new LinkedList<Data>();
		this.sorted = new ArrayList<HashMap<Integer, Data>>();
		this.storer = storer;

		new Thread(this).start();
	}

	public synchronized void add(Data d) {
		queue.add(d);
	}

	private synchronized void newHashMap(Data data) {
		HashMap<Integer,Data> newHash = new HashMap<Integer, Data>();
		newHash.put(data.getStn(), data);
		sorted.add(newHash);
	}

	@Override
	public void run() {
		while (true) {
			try {
				Thread.sleep(100);
			} catch (Exception e){}

			while (!queue.isEmpty()) {
				try {
					synchronized(this) {
						Data data = queue.poll();
						boolean isPut = false;

						for (HashMap<Integer, Data> i : sorted) {
							if (!i.containsKey(data.getStn())) {
								i.put(data.getStn(), data);
								if (i.size() >= 8000) {
									storer.addAllToBuffer(i);
									sorted.remove(i);
								}
								isPut = true;
								break;
							}						
						}
						if (!isPut) {
							newHashMap(data);
						}
					}
				} catch (Exception e) {

				}
			}
		}		
	}
}
